import { defineStore } from 'pinia';

// 定义产品类型
interface Product {
  id: number;
  name: string;
  price: number;
  quantity?: number;
  image?: string;
  description?: string;
}

export const useCartStore = defineStore('cart', {
  state: () => ({
    products: [] as Product[],
    total: 0,
  }),
  getters: {
    cartProducts: (state) => state.products,
    cartTotal: (state) => state.total,
  },
  actions: {
    addProduct(product: Product) {
      const existingProduct = this.products.find(
        (item) => item.id === product.id
      );

      if (existingProduct) {
        existingProduct.quantity = (existingProduct.quantity || 0) + 1;
      } else {
        this.products.push({ ...product, quantity: 1 });
      }

      this.updateTotal();
    },

    removeProduct(id: number) {
      this.products = this.products.filter(
        (product) => product.id !== id
      );
      this.updateTotal();
    },

    updateQuantity(id: number, quantity: number) {
      const product = this.products.find(
        (item) => item.id === id
      );

      if (product) {
        product.quantity = quantity;
      }

      this.updateTotal();
    },

    updateTotal() {
      this.total = this.products.reduce(
        (acc, product) => acc + product.price * (product.quantity || 0),
        0
      );
    },

    clearCart() {
      this.products = [];
      this.total = 0;
    },
  },
});